package hhm.android.main

import android.content.Intent
import android.graphics.Color
import android.text.Html
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.activity.result.ActivityResultLauncher
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.app.hubert.guide.NewbieGuide
import com.app.hubert.guide.model.GuidePage
import com.bumptech.glide.Glide
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.trello.rxlifecycle4.RxLifecycle
import com.trello.rxlifecycle4.android.FragmentEvent
import hhm.android.base.fragment.NewLazyFragment
import hhm.android.library.LogUtils

import hhm.android.library.bus.annotation.BusReceiver
import hhm.android.library.chart.charts.LineChart
import hhm.android.library.chart.components.Legend
import hhm.android.library.chart.data.Entry
import hhm.android.library.chart.data.LineData
import hhm.android.library.chart.data.LineDataSet
import hhm.android.library.chart.formatter.DateValueFormatter
import hhm.android.library.chart.formatter.IFillFormatter
import hhm.android.library.chart.highlight.Highlight
import hhm.android.library.chart.interfaces.datasets.ILineDataSet
import hhm.android.library.chart.listener.OnChartValueSelectedListener
import hhm.android.library.utils.BackListener
import hhm.android.library.utils.OnMultiClickListener
import siau.android.base.*
import siau.android.http.model.*
import siau.android.library.KeyString
import hhm.android.main.shoeSizeHistory.ShoeSizeHistoryListActivity
import hhm.android.main.history.HistoryListActivity
import siau.android.base.enum.HeightClass
import siau.android.base.enum.WeightClass
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

open class OneFragmentInner() : NewLazyFragment() {

    companion object {
        const val PAGE_STATE_WEIGHT = 1
        const val PAGE_STATE_HEIGHT = 2
    }

    private var pageType: Int = 1
    var childIdNow = -1

    constructor(type: Int, hasOut: Boolean, outShow: Boolean) : this() {
        pageType = type
        isHasOut = hasOut
        isOutShow = outShow
    }

    private lateinit var ivTopNoData: ImageView
    private lateinit var tvTopNoData: TextView
//    private lateinit var startTest: TextView
    private lateinit var tvTopDate: TextView
    private lateinit var tvTopTime: TextView
    private lateinit var tvTopWeight: TextView
    private lateinit var smart: SmartRefreshLayout
    private lateinit var ll: LinearLayout
    private lateinit var ivWrite: ImageView
    private lateinit var ivFootWrite: ImageView
    private lateinit var ivFootClassChange: ImageView
    private lateinit var tvShoeSizeType: TextView
    private lateinit var chart: LineChart
    private lateinit var footHistoryList: LinearLayout
    private lateinit var chartLl: LinearLayout
    private lateinit var chartPage: LinearLayout
    private lateinit var centerHistoryList: LinearLayout
    protected var list = ArrayList<ChildModel>()
    private lateinit var tvNoData: TextView
    private lateinit var tvSetDataTop: TextView
    private lateinit var clSetData: ConstraintLayout
    private lateinit var ivSetDataBottom: ImageView
    private lateinit var tvSetDataBottom: TextView
    private lateinit var tvFootDate: TextView
    private lateinit var tvFootValue: TextView
    private lateinit var tvFootSize: TextView
    private lateinit var bottom: ConstraintLayout
    private lateinit var recycler: RecyclerView
    private var childAdapter: ChildAdapter? = null
    private lateinit var start: ActivityResultLauncher<Intent>

    override fun getContentViewId(): Int {
        return R.layout.fragment_one_viewpager_inner
    }

    override fun initView(view: View?) {
        super.initView(view)
        ll = view?.findViewById(R.id.fragment_one_viewpager_inner_ll)!!

        smart = view.findViewById(R.id.fragment_one_viewpager_inner_smart)
        ivWrite = view.findViewById(R.id.fragment_one_viewpager_inner_write)
        recycler = view.findViewById(R.id.fragment_one_viewpager_inner_recycler)
        chart = view.findViewById(R.id.fragment_one_viewpager_inner_chart)
        footHistoryList = view.findViewById(R.id.fragment_one_viewpager_inner_bottom_foot_history_list)
        chartPage = view.findViewById(R.id.fragment_one_viewpager_inner_center_chart)
        centerHistoryList = view.findViewById(R.id.fragment_one_viewpager_inner_center_history)
        ivFootWrite = view.findViewById(R.id.fragment_one_viewpager_inner_bottom_iv)
        ivFootClassChange = view.findViewById(R.id.fragment_one_viewpager_inner_bottom_shoe_size_change_iv)
        tvShoeSizeType = view.findViewById(R.id.fragment_one_viewpager_inner_bottom_shoe_size_type)
        chartLl = view.findViewById(R.id.fragment_one_viewpager_inner_chart_ll)
        ivTopNoData = view.findViewById(R.id.fragment_one_viewpager_inner_top_iv)
        tvTopNoData = view.findViewById(R.id.fragment_one_viewpager_inner_top_tv)
        tvTopDate = view.findViewById(R.id.fragment_one_viewpager_inner_last_date)
        tvTopTime = view.findViewById(R.id.fragment_one_viewpager_inner_last_time)
        tvTopWeight = view.findViewById(R.id.fragment_one_viewpager_inner_last_weight)
        tvFootDate = view.findViewById(R.id.fragment_one_viewpager_inner_foot_date)
        tvFootValue = view.findViewById(R.id.fragment_one_viewpager_inner_foot_value)
        tvFootSize = view.findViewById(R.id.fragment_one_viewpager_inner_foot_size)

//        startTest = view.findViewById(R.id.fragment_one_viewpager_inner_start_test)

        bottom = view.findViewById(R.id.fragment_one_viewpager_inner_bottom)
        val ivTypeTop: ImageView = view.findViewById(R.id.fragment_one_viewpager_inner_top_type_iv_left)
        val tvTypeCenter: TextView = view.findViewById(R.id.fragment_one_viewpager_inner_center_type_tv)
        tvNoData = view.findViewById(R.id.fragment_one_viewpager_inner_top_no_data_tv)
        clSetData = view.findViewById(R.id.fragment_one_viewpager_inner_top_data_tv)
        tvSetDataTop = view.findViewById(R.id.fragment_one_viewpager_inner_weight_data_tv_top)
        ivSetDataBottom = view.findViewById(R.id.fragment_one_viewpager_inner_weight_data_iv_bottom)
        tvSetDataBottom = view.findViewById(R.id.fragment_one_viewpager_inner_weight_data_tv_bottom_right)
        if (pageType == PAGE_STATE_HEIGHT) {
            bottom.visibility = View.GONE
            ivTypeTop.setImageResource(R.mipmap.height_machine)
            tvTypeCenter.text = getText(R.string.baby_height_history)
            tvTopNoData.text = getString(R.string.height_you_never_test_try_it)
        } else if (pageType == PAGE_STATE_WEIGHT) {
            ivTypeTop.setImageResource(R.mipmap.weight_machine)
            tvTypeCenter.text = getText(R.string.baby_weight_history)
            tvTopNoData.text = getString(R.string.weight_you_never_test_try_it)
        }

        start = registerForActivityResult(IntentIntActivityResultContact()) {
            if (it == 1001) {//手动输入完成之后刷新接口
                getData()
            }
        }
        initChildren()
    }

    /**
     * boolean值 留的口子 用来保留之前选择的孩子 新增加孩子的时候 跳转页面之前选了第n个孩子 加入boolean值，
     * 就能在孩子列表刷新之后指向对应的孩子，否则孩子列表一旦刷新，只能默认指向第一个孩子
     */
    private fun initChildren() {
        list = ArrayList()

        val lm = LinearLayoutManager(activity)
        lm.orientation = LinearLayoutManager.HORIZONTAL
        recycler.layoutManager = lm

        childAdapter = activity?.let {
            ChildAdapter(it, list, { i ->
                childIdNow = list[i].childId
                SBApplication.communityChildId = childIdNow
                childAdapter?.notifyDataSetChanged()
                getData()
            }, object : BackListener {
                override fun callBack() {
                    ARouter.getInstance().build(BABY_ROUTE).withInt(KeyString.type, 0).navigation()
                }
            })
        }!!
        recycler.adapter = childAdapter
    }

    override fun initData() {
        super.initData()
        getData()
    }

    override fun initEvent() {
        super.initEvent()
        //点击测量按钮
//        startTest.setOnClickListener(object : OnMultiClickListener() {
//            override fun onMultiClick(v: View?) {
//                if (!SBApplication.startCalculate.value!!) {
//                    if (SBApplication.userData.children?.size!! == 1) {
//                        clickStartTest(SBApplication.userData.children!![0].childId)
//                    } else {
//                        val bottomSingleBabySelectSheet = activity?.let { it ->
//                            BottomSingleBabySelectSheet(it, SBApplication.startCalculate.value!!, pageType, childIdNow, list, object : GetChildIdListener {
//                                override fun getChildId(childId: Int) {
//                                    clickStartTest(childId)
//                                }
//                            })
//                        }
//                        bottomSingleBabySelectSheet!!.show()
//                    }
//                }
//            }
//        })
        //鞋码记录
        footHistoryList.setOnClickListener {
            val i = Intent(activity, ShoeSizeHistoryListActivity::class.java)
            i.putExtra(KeyString.childId, childIdNow)
            startActivity(i)
        }
        //手动输入
        ivWrite.setOnClickListener(object : OnMultiClickListener() {
            override fun onMultiClick(v: View?) {
                if (SBApplication.userData.children?.size!! == 1) {
                    clickIvWrite(SBApplication.userData.children!![0].childId)
                } else {
                    val bottomSingleBabySelectSheet = activity?.let {
                        BottomSingleBabySelectSheet(it, /*false,*/ pageType, childIdNow, list, object : GetChildIdListener {
                            override fun getChildId(childId: Int) {
                                clickIvWrite(childId)
                            }
                        })
                    }
                    bottomSingleBabySelectSheet!!.show()
                }
            }
        })
        //图表页面
        chartPage.setOnClickListener {
            val i = Intent(activity, SeeTrendsActivity::class.java)
            i.putExtra(KeyString.childId, childIdNow)
            i.putExtra(KeyString.dataType, pageType)
            startActivity(i)
        }
        //身高体重历史记录页面
        centerHistoryList.setOnClickListener {
            val i = Intent(activity, HistoryListActivity::class.java)
            i.putExtra(KeyString.childId, childIdNow)
            i.putExtra(KeyString.type, pageType)
            startActivity(i)
        }
        //鞋码手动输入
        ivFootWrite.setOnClickListener {
            if (SBApplication.userData.children?.size!! == 1) {
                clickIvFootWrite(SBApplication.userData.children!![0].childId)
            } else {
                val bottomSingleBabySelectSheet = activity?.let {
                    BottomSingleBabySelectSheet(it, /*false,*/ pageType, childIdNow, list, object : GetChildIdListener {
                        override fun getChildId(childId: Int) {
                            clickIvFootWrite(childId)
                        }
                    })
                }
                bottomSingleBabySelectSheet!!.show()
            }
        }
        smart.setEnableLoadMore(false)
        smart.setOnRefreshListener {
            getData()
        }
        chartLl.setOnClickListener(object : OnMultiClickListener() {
            override fun onMultiClick(v: View?) {
                val i = Intent(activity, SeeTrendsActivity::class.java)
                i.putExtra(KeyString.childId, childIdNow)
                i.putExtra(KeyString.dataType, pageType)
                startActivity(i)
            }
        })
        //切换鞋码单位
        ivFootClassChange.setOnClickListener(object : OnMultiClickListener() {
            override fun onMultiClick(v: View?) {
                HttpHelper().shoeSizeList()?.subscribe({ list ->
                    val bottomSheet = activity?.let {
                        BottomShoeSizeClassSelectSheet(it, list, object : GetShoeSizeTypeListener {
                            override fun getShoeSizeType(bean: ShoeSizeListModel) {
                                val r = ShoesSizeTypeModel(bean.type)
                                SBApplication.userData.shoesType.type = bean.type
                                SBApplication.userData.shoesType.typeName = bean.typeName
                                HttpHelper().swapShoeSizeType(r)?.subscribe({
                                    getData()
                                }, { it ->
                                    showToast(it.message)
                                })
                            }
                        })
                    }
                    bottomSheet!!.show()
                }, {
                    showToast(it.message)
                })

            }
        })

//        SBApplication.startCalculate.observe(this, {
//            if (!it && SBApplication.calculateType == pageType && SBApplication.calculateChild == childIdNow && !TextUtils.isEmpty(KeyString.token)) {
//                getData()
//            }
//        })
//        /**
//         * 根据捕获的日志，在BluetoothUtil连接上或者断开连接设备之后 这里的方法会被执行到 内部有一个循环
//         * SBApplication.getBlueToothUtils().connectDevice?.forEach
//         * 当循环进行时，如果又连接或者断开了设备，就会发生崩溃（因为循环过程中在其他地方改变了列表数据）
//         */
//        SBApplication.getBlueToothUtils().connectDeviceNum?.observe(this, {
//            if (SBApplication.startCalculate.value == true && SBApplication.calculateType == pageType && SBApplication.calculateChild == childIdNow) {
//                startTest.setBackgroundResource(R.drawable.rectangle_circle_grey_e6)
//                var hasConnect = false
//                SBApplication.getBlueToothUtils().connectDevice?.forEach {
//                    if (it.deviceType == pageType) {
//                        hasConnect = true
//                    }
//                }
//                if (hasConnect) {
//                    startTest.text = getString(R.string.calculating)
//                } else {
//                    startTest.text = getString(R.string.connecting)
//                }
//            }
//        })
    }

    override fun getData() {

        HttpHelper().myBabyList()?.subscribe({

            list.clear()
            list.addAll(it)
            SBApplication.userData.children = it
            var has = false
            list.forEach { i ->
                if (i.childId == childIdNow && i.childId != -1) {
                    i.select = true
                    SBApplication.communityChildId = i.childId
                    has = true
                }
            }
            if (!has && list.size > 0) {
                list[0].select = true
                SBApplication.communityChildId = list[0].childId
                childIdNow = list[0].childId
            }

            if (SBApplication.userData.isCreator == 1) {
                val c = ChildModel(-1, "", "", false, -1, 0, 0, -1.0, -1.0)
                list.add(c)
            }

            childAdapter?.setData(list)

            var cla = ""
            if (pageType == PAGE_STATE_WEIGHT) {
                when (SBApplication.userData.weightUnit) {
                    WeightClass.KG.msg -> cla = getString(R.string.class_kg)
                    WeightClass.JIN.msg -> cla = getString(R.string.class_jin)
                    WeightClass.LB.msg -> cla = getString(R.string.class_bang)
                }
            } else {
                when (SBApplication.userData.heightUnit) {
                    HeightClass.CM.msg -> cla = getString(R.string.class_cm)
                    HeightClass.FT.msg -> cla = getString(R.string.class_ft)
                }
            }

            if (childIdNow == -1) {
                return@subscribe
            }
            val request = HomeRequest(pageType, childIdNow)
            HttpHelper().getChildHomeData(request)?.compose(RxLifecycle.bindUntilEvent(lifecycle(), FragmentEvent.STOP))?.subscribe({ it ->
                smart.finishRefresh()
//                if (SBApplication.startCalculate.value!! && SBApplication.calculateType == pageType && SBApplication.calculateChild == childIdNow) {
//                    homeCalculateData(cla, it.lastRecords)
//                } else {
                    when (it.lastRecords.size) {
                        2 -> {
                            homeTopSetData(cla, it.lastRecords[0], it.lastRecords[1])
                        }
                        1 -> {
                            homeTopSetOneData(cla, it.lastRecords[0])
                        }
                        else -> {
                            homeTopNoData()
                        }
                    }
//                }
                initChart(it.recordList)
            }, { e ->
                smart.finishRefresh()
                showToast(e.message)
            })
            if (pageType == PAGE_STATE_WEIGHT) {
                val r = ChildIdModel(childIdNow)
                HttpHelper().getFootRecord(r)?.compose(RxLifecycle.bindUntilEvent(lifecycle(), FragmentEvent.STOP))?.subscribe({ it ->
                    val sdf = SimpleDateFormat("MM月dd日")
                    tvShoeSizeType.text = SBApplication.userData.shoesType.typeName
                    if (it.date == 0L) {
                        tvFootDate.text = "- -"
                    } else {
                        tvFootDate.text = sdf.format(Date(it.date))
                    }
                    if (it.size.isNaN() || it.size == 0.0) {
                        tvFootSize.text = "- -"
                    } else {
                        tvFootSize.text = it.size.toString()
                    }
                    if (it.value.isNaN() || it.value == 0.0) {
                        tvFootValue.text = "- -"
                    } else {
                        tvFootValue.text = it.value.toString()
                    }
                }, { e ->
                    showToast(e.message)
                })

                if (SBApplication.userData.footGuide == 1) {

                    SBApplication.userData.footGuide = 0

                    NewbieGuide.with(this).setLabel("guide_shoe_size").alwaysShow(true).addGuidePage(
                        GuidePage.newInstance().addHighLight(bottom).setLayoutRes(R.layout.guide_shoe_size)
                    ).show()

                }
            }

        }, {
            showToast(it.message)
        })

        //转让家庭之后去掉加号
        if (SBApplication.userData.isCreator != 1 && list.size > 0 && list[list.size - 1].childId == -1) {
            list.removeAt(list.size - 1)
            childAdapter?.notifyDataSetChanged()
        }
    }

    private fun initChart(recordList: ArrayList<ChartModel>) {
        val sdf = SimpleDateFormat("yyyy-MM-dd")
        if (chart.data == null) {
            chart.setBackgroundColor(Color.WHITE)
            chart.setTouchEnabled(false)
            chart.setDrawGridBackground(false)

            // force pinch zoom along both axis
            chart.setMaxVisibleValueCount(0)

            val values = java.util.ArrayList<Entry>()
            for (i in 0 until recordList.size) {
                val y = recordList[i].recordValue.toFloat()
                values.add(Entry(sdf.parse(recordList[i].recordDate).time.toFloat(), y))
            }

            val set1 = LineDataSet(values, "")

            set1.mode = LineDataSet.Mode.HORIZONTAL_BEZIER

            set1.lineWidth = 3f
            set1.circleRadius = 3f

            set1.formLineWidth = 0f
            set1.formSize = 15f

            set1.valueTextSize = 9f

            //背景渐变色
            val drawable = activity?.let { ContextCompat.getDrawable(it, R.drawable.fade_blue) }
            set1.fillDrawable = drawable

            set1.setDrawFilled(true)
            set1.fillFormatter = IFillFormatter { _, _ -> chart.axisLeft.axisMinimum }

            val dataSets = ArrayList<ILineDataSet>()
            dataSets.add(set1)

            val data = LineData(dataSets)

            chart.axisLeft.setDrawLabels(false)
            chart.axisLeft.setDrawAxisLine(false)
            chart.axisLeft.setDrawGridLines(false)
            chart.axisRight.setDrawLabels(false)
            chart.axisRight.setDrawAxisLine(false)
            chart.axisRight.setDrawGridLines(false)
            chart.xAxis.setDrawLabels(false)
            chart.xAxis.setDrawAxisLine(false)
            chart.xAxis.setDrawGridLines(false)

            chart.setBorderColor(Color.parseColor("#ffffff"))
            chart.description = null

            //隐藏左下角小方块  //图例
            val l: Legend = chart.legend
            l.isEnabled = false

            chart.xAxis.valueFormatter = DateValueFormatter()

            chart.data = data
        } else {
            val cData = chart.data
            cData.dataSets.clear()

            val values = java.util.ArrayList<Entry>()
            for (i in 0 until recordList.size) {
                val y = recordList[i].recordValue.toFloat()
                values.add(Entry(sdf.parse(recordList[i].recordDate).time.toFloat(), y))
            }

            val set1 = LineDataSet(values, "")

            set1.mode = LineDataSet.Mode.HORIZONTAL_BEZIER

            set1.lineWidth = 3f
            set1.circleRadius = 3f

            set1.formLineWidth = 0f
            set1.formSize = 15f

            set1.valueTextSize = 9f

            //背景渐变色
            val drawable = activity?.let { ContextCompat.getDrawable(it, R.drawable.fade_blue) }
            set1.fillDrawable = drawable

            set1.setDrawFilled(true)
            set1.fillFormatter = IFillFormatter { _, _ -> chart.axisLeft.axisMinimum }

            cData.dataSets.add(set1)
            cData.notifyDataChanged()
            chart.notifyDataSetChanged()
            chart.invalidate()
        }
    }

    private fun homeCalculateData(cla: String, lastRecords: ArrayList<HomeModel>) {
        ivTopNoData.visibility = View.VISIBLE
        tvTopNoData.visibility = View.VISIBLE
        tvTopDate.visibility = View.GONE
        tvTopTime.visibility = View.GONE
        tvTopWeight.visibility = View.GONE
        activity?.let { Glide.with(it).load(R.mipmap.measuring).into(ivTopNoData) }
        tvTopNoData.text = getString(R.string.calculate_now)

        when (lastRecords.size) {
            2 -> {
                tvNoData.visibility = View.GONE
                clSetData.visibility = View.VISIBLE
                val sdf = SimpleDateFormat("yyyy年MM月dd日")
                val sdfTime = SimpleDateFormat("HH:mm")
                tvTopDate.text = sdf.format(Date(lastRecords[0].recordTime))
                tvTopTime.text = sdfTime.format(Date(lastRecords[0].recordTime))
                tvTopWeight.text = Html.fromHtml(activity?.let { analyseHomeDataBeforeSet(it, lastRecords[0].recordValue.toString(), pageType, cla) }, null, HtmlTagHandler("homeFont"))

                if (lastRecords[0].growth > 0) {//胖了 高了
                    ivSetDataBottom.setImageResource(R.mipmap.bigger)
                    tvSetDataTop.text = analyseDataBeforeSet(lastRecords[0].growth.toString(), pageType, cla)
                } else {
                    ivSetDataBottom.setImageResource(R.mipmap.smaller)
                    tvSetDataTop.text = analyseDataBeforeSet(lastRecords[0].growth.toString().replace("-", ""), pageType, cla)
                }
                val time = sdf.format(Date(lastRecords[1].recordTime))
                tvSetDataBottom.text = getString(R.string.match) + time
            }
            1 -> {
                tvNoData.visibility = View.VISIBLE
                clSetData.visibility = View.GONE
                val sdf = SimpleDateFormat("yyyy年MM月dd日")
                val sdfTime = SimpleDateFormat("HH:mm")
                tvTopDate.text = sdf.format(Date(lastRecords[0].recordTime))
                tvTopTime.text = sdfTime.format(Date(lastRecords[0].recordTime))
                tvTopWeight.text = Html.fromHtml(activity?.let { analyseHomeDataBeforeSet(it, lastRecords[0].recordValue.toString(), pageType, cla) }, null, HtmlTagHandler("homeFont"))
            }
            else -> {
                tvNoData.visibility = View.VISIBLE
                clSetData.visibility = View.GONE
            }
        }

//        startTest.setBackgroundResource(R.drawable.rectangle_circle_grey_e6)
//        var hasConnect = false
//        SBApplication.getBlueToothUtils().connectDevice!!.forEach {
//            if (it.deviceType == pageType) {
//                hasConnect = true
//            }
//        }
//        if (hasConnect) {
//            startTest.text = getString(R.string.calculating)
//        } else {
//            startTest.text = getString(R.string.connecting)
//        }
    }

    private fun homeTopNoData() {
        tvNoData.visibility = View.VISIBLE
        clSetData.visibility = View.GONE
        ivTopNoData.visibility = View.VISIBLE
        tvTopNoData.visibility = View.VISIBLE
        tvTopDate.visibility = View.GONE
        tvTopTime.visibility = View.GONE
        tvTopWeight.visibility = View.GONE
        if (pageType == PAGE_STATE_HEIGHT) {
            tvTopNoData.text = getString(R.string.height_you_never_test_try_it)
        } else {
            tvTopNoData.text = getString(R.string.weight_you_never_test_try_it)
        }
        ivTopNoData.setImageResource(R.mipmap.no_data_bg)

//        startTest.setBackgroundResource(R.drawable.rectangle_circle_maincolor)
//        startTest.text = getString(R.string.start_test)
    }

    private fun homeTopSetOneData(cla: String, first: HomeModel) {
        tvNoData.visibility = View.VISIBLE
        clSetData.visibility = View.GONE
        ivTopNoData.visibility = View.GONE
        tvTopNoData.visibility = View.GONE
        tvTopDate.visibility = View.VISIBLE
        tvTopTime.visibility = View.VISIBLE
        tvTopWeight.visibility = View.VISIBLE
        val sdf = SimpleDateFormat("yyyy年MM月dd日")
        val sdfTime = SimpleDateFormat("HH:mm")
        tvTopDate.text = sdf.format(Date(first.recordTime))
        tvTopTime.text = sdfTime.format(Date(first.recordTime))
        tvTopWeight.text = Html.fromHtml(activity?.let { analyseHomeDataBeforeSet(it, first.recordValue.toString(), pageType, cla) }, null, HtmlTagHandler("homeFont"))

//        startTest.setBackgroundResource(R.drawable.rectangle_circle_maincolor)
//        startTest.text = getString(R.string.start_test)
    }

    private fun homeTopSetData(cla: String, first: HomeModel, second: HomeModel) {
        tvNoData.visibility = View.GONE
        clSetData.visibility = View.VISIBLE
        ivTopNoData.visibility = View.GONE
        tvTopNoData.visibility = View.GONE
        tvTopDate.visibility = View.VISIBLE
        tvTopTime.visibility = View.VISIBLE
        tvTopWeight.visibility = View.VISIBLE

        val sdf = SimpleDateFormat("yyyy年MM月dd日")
        val sdfTime = SimpleDateFormat("HH:mm")
        tvTopDate.text = sdf.format(Date(first.recordTime))
        tvTopTime.text = sdfTime.format(Date(first.recordTime))
        tvTopWeight.text = Html.fromHtml(activity?.let { analyseHomeDataBeforeSet(it, first.recordValue.toString(), pageType, cla) }, null, HtmlTagHandler("homeFont"))

        if (first.growth > 0) {//胖了 高了
            ivSetDataBottom.setImageResource(R.mipmap.bigger)
            tvSetDataTop.text = analyseDataBeforeSet(first.growth.toString(), pageType, cla)
        } else {
            ivSetDataBottom.setImageResource(R.mipmap.smaller)
            tvSetDataTop.text = analyseDataBeforeSet(first.growth.toString().replace("-", ""), pageType, cla)
        }
        val time = sdf.format(Date(second.recordTime))
        tvSetDataBottom.text = getString(R.string.match) + time

//        startTest.setBackgroundResource(R.drawable.rectangle_circle_maincolor)
//        startTest.text = getString(R.string.start_test)
    }

    @BusReceiver
    fun StringEvent(event: String) {
        if (event == "ifHomeThenRefresh") {
            if (isVisible) {
                getData()
            }
        }
    }

//    private fun clickStartTest(childId: Int) {
//        childIdNow = childId
//        list.forEach { i ->
//            i.select = i.childId == childIdNow
//        }
//        childAdapter?.notifyDataSetChanged()
//        getData()
//
////        SBApplication.startCalculate.value = true
////        SBApplication.calculateType = pageType
////        SBApplication.calculateChild = childIdNow
//
//        //开启动画
//        ivTopNoData.visibility = View.VISIBLE
//        tvTopNoData.visibility = View.VISIBLE
//        tvTopDate.visibility = View.GONE
//        tvTopTime.visibility = View.GONE
//        tvTopWeight.visibility = View.GONE
//        activity?.let { Glide.with(it).load(R.mipmap.measuring).into(ivTopNoData) }
//        tvTopNoData.text = getString(R.string.calculate_now)
//
////        startTest.setBackgroundResource(R.drawable.rectangle_circle_grey_e6)
////        var hasConnect = false
////        SBApplication.getBlueToothUtils().connectDevice!!.forEach {
////            if (it.deviceType == pageType) {
////                hasConnect = true
////            }
////        }
////        if (hasConnect) {
////            startTest.text = getString(R.string.calculating)
////        } else {
////            startTest.text = getString(R.string.connecting)
////        }
//
//        SBApplication.getBlueToothUtils().pairBlueTooth()
//    }

    private fun clickIvWrite(childId: Int) {
        childIdNow = childId
        var doubleWidth = 0.0
        var doubleHeight = 0.0
        list.forEach { i ->
            if (i.childId == childIdNow) {
                i.select = true
                doubleHeight = i.height
                doubleWidth = i.weight
            } else {
                i.select = false
            }

        }
        childAdapter?.notifyDataSetChanged()
        getData()

        when (pageType) {
            PAGE_STATE_WEIGHT -> {
                val i = Intent(activity, InputWeightByHandActivity::class.java)
                i.putExtra(KeyString.childId, childIdNow)
                i.putExtra(KeyString.data, doubleWidth)
                start.launch(i)
            }
            PAGE_STATE_HEIGHT -> {
                val i = Intent(activity, InputHeightByHandActivity::class.java)
                i.putExtra(KeyString.childId, childIdNow)
                i.putExtra(KeyString.data, doubleHeight)
                start.launch(i)
            }
        }
    }

    private fun clickIvFootWrite(childId: Int) {
        childIdNow = childId
        list.forEach { i ->
            i.select = i.childId == childIdNow
        }
        childAdapter?.notifyDataSetChanged()
        getData()

        val i = Intent(activity, InputFootByHandActivity::class.java)
        i.putExtra(KeyString.childId, childIdNow)
        i.putExtra(KeyString.data, tvFootValue.text.toString())
        start.launch(i)
    }

    open fun selectSomeChild(childId: Int) {
        childIdNow = childId
        SBApplication.communityChildId = childId
        list?.forEach { i ->
            i.select = i.childId == childIdNow
        }
        childAdapter?.notifyDataSetChanged()
        getData()
    }
}